﻿using CKS.Core.Framework;
using CKS.Core.Framework.Models;
using CKS.PLC.Core.Cache;
using CKS.PLC.Core.Event;
using CKS.Schedule;
using FreeSql;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace CKS.PLC.Core.CronJob
{
    [Schedule]
    public class SyncDataJobs : CronJobBase
    {
        public SyncDataJobs() : base("数据库同步服务", "0/1 * * * * ?") 
        {

        }
        Dictionary<string,SyncDataJobBase> jobs = new Dictionary<string,SyncDataJobBase>();
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var configs =InternalApp.Fsql.Select<DatabaseCollectionConfig>().Where(a => a.Nullity == false).ToList();
           
            foreach (var config in configs) {
                SyncDataJobBase job = null;
                if (!jobs.ContainsKey(config.BusinessCode))
                {
                    job = new SyncDataJobBase(config.DeviceName + "数据库采集", config);
                    jobs[config.BusinessCode] = job;
                    _= job.StartAsync(CancellationToken.None);
                   
                }
                else
                    job = jobs[config.BusinessCode];
               
            }
            //如果被删除了就取消
            var jdics =jobs.Keys.ToList();
            foreach (var jdic in jdics)
            {
                var exjob =configs.Find(a => a.BusinessCode == jdic);
                if(exjob == null)
                {
                    var job = jobs[jdic];
                    _=job.StopAsync(CancellationToken.None);
                    jobs.Remove(jdic);
                }
            }


            await Task.CompletedTask;
        }
    }

 
    //public class OP110UTSyncDataJob : SyncDataJobBase
    //{
    //    public OP110UTSyncDataJob() : base("UT数据库采集", "ut01")
    //    {
    //    }
    //}

  
    //public class OP150UTSyncDataJob : SyncDataJobBase
    //{
    //    public OP150UTSyncDataJob() : base("氦检数据库采集", "hc01")
    //    {
    //    }
    //}


    //从数据库加载业务代码，动态执行






}
